# coding=utf-8
# 这是一个示例 Python 脚本。

# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
import os
import paramiko
####测试@@######33
yuancheng2

import fnmatch  #解决*号通配符匹配问题

def ssh_cmd(ip,port, cmd, user, passwd):

    result = ""

    try:

        ssh = paramiko.SSHClient()

        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh.connect(ip, port, user, passwd,timeout=10)

        stdin, stdout, stderr =ssh.exec_command(cmd)

        result = stdout.read()

        ssh.close()
        print("ssh_cmd yes.")

    except:

        print("ssh_cmd err.")

    return result

def sftp_download(hostname, port, username, password , remotepath, localpath):

    # 获取Transport实例
    tran = paramiko.Transport((hostname, port))

    # 连接SSH服务端，使用password
    tran.connect(username=username, password=password)
    # 获取SFTP实例
    sftp = paramiko.SFTPClient.from_transport(tran)
    # 执行下载动作

    sftp.get(remotepath, localpath)

def sftp_put(hostname, port, username, password , localpath, remotepath):

    # 获取Transport实例
    tran = paramiko.Transport((hostname, port))

    # 连接SSH服务端，使用password
    tran.connect(username=username, password=password)
    # 获取SFTP实例
    sftp = paramiko.SFTPClient.from_transport(tran)

    # 执行上传动作
    sftp.put(localpath, remotepath)

    sftp.close()

# ------------------------- Functions -------------------------
# 入口，给两个日期参数
# ------------------------- Functions -------------------------
# 入口，给两个日期参数
# def Main(since: datetime, today: datetime):
#     username = '***'
#     password = '***'
#     server = ("***", 22)
#
#     with paramiko.Transport(server) as transport:
#         transport.connect(username=username, password=password)
#         with paramiko.SFTPClient.from_transport(transport) as sftp:
#             while since <= today:
#                 doGET(since, sftp)
#                 since += timedelta(1)ya
#
# # 主体逻辑部分
# def doGET(today: datetime, sftp: paramiko.SFTPClient):
#     remote_path = "/download/GEN/%s/" % today.strftime("%Y%m%d")
#     local_path = "/home/***"
#     # 有可能当天没有文件夹
#     try:
#         sftp.chdir(remote_path)
#     except Exception as e:
#         logger.error("Failed when chdir [%s]: %s" % (remote_path, e))
#         return
#     # 文件夹存在，就下载所有文件
#     for remote_filename in sftp.listdir():
#         local_filepath = os.path.join(local_path, today.strftime("%Y%m%d") + "_" + remote_filename)
#         try:
#             sftp.get(remote_filename, local_filepath)
#         except Exception as e:
#             logger.error("Failed when get %s: %s" % ([remote_filename, local_filepath], e))
#         else:
#             logger.info("Success get %s" % ([remote_filename, local_filepath],))

# ------------------------- Main -------------------------
# if __name__ == "__main__":
#     import argparse
#
#     PARSER = argparse.ArgumentParser(
#         description="""none""")
#     PARSER.add_argument('--since', type=str, default="", help="Loop 'since' to 'today'. format 20190131.")
#     PARSER.add_argument('--today', type=str, default=(datetime.now() - timedelta(1)).strftime('%Y%m%d'),
#                         help='Default yesterday. format 20190131.')
#     ARGS = PARSER.parse_args()
#     today = datetime.strptime(ARGS.today, "%Y%m%d")
#     since = datetime.strptime(ARGS.since, "%Y%m%d") if len(ARGS.since) else today
#     # run
#     Main(since, today)




#####/home/aiox/* /home/aiox/*.war 处理*通配符匹配问题#####
def downloadfiles(hostname, port, username, password , localpath, remotepath):

    # 获取Transport实例
    tran = paramiko.Transport((hostname, port))

    # 连接SSH服务端，使用password
    tran.connect(username=username, password=password)
    # 获取SFTP实例
    sftp = paramiko.SFTPClient.from_transport(tran)

    for remote_filename in sftp.listdir(remotepath):
        ###打印sftp远程服务器下所有目录
        print(remote_filename)

    # 执行上传动作
    sftp.put(localpath, remotepath)

    sftp.close()


def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print("Hi, {0}".format(name))  # 按 Ctrl+F8 切换断点。


# 按间距中的绿色按钮以运行脚本。
if __name__ == '__main__':
    print_hi('PyCharm')
    ssh_cmd("192.168.123.175",22,"mkdir -p /root/1","root","1236")
    sftp_download("192.168.123.175",22,"root","1236","/root/kubernetes-server-linux-amd64.tar.gz","C:\Users\sncu\Desktop\kubernetes-server-linux-amd64.tar.gz")


# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
